﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using ClosedXML.Excel;

namespace HmLab.Func2;

internal class LbReadCopyConfig {

  /// <summary>
  /// ReadCopyConfig
  /// <see cref="Haimen.Func2.MonthInputCollector"/>
  /// </summary>
  public void Run() {
    string cfgPath = @"E:\work_etc\nina\2023haimen2\workshop_cslab\输O入func2b\输O入\dev\path.xlsx";
    Console.WriteLine(cfgPath);

    using FileStream stream = _excelUtil.OpenRead(cfgPath);
    using XLWorkbook configBook = new(stream);

    IXLWorksheet sheet = configBook.Worksheets.Single();
    //Console.WriteLine(sheet.Name);

    int lastRow = sheet.LastRowUsed().RowNumber();
    CopyCfg[] cfgList = Enumerable.Range(1, lastRow)
      .Select(r => ParseRow(sheet, r))
      .ToArray();

    foreach (var cfg in cfgList) {
      Console.WriteLine(cfg);
    }
  }

  record CopyCfg(string File, string Sheet, string Range, int Sort);
  CopyCfg ParseRow(IXLWorksheet sheet, int num) {
    IXLRow row = sheet.Row(num);
    var CellStr = (int c) => row.Cell(c).GetString();

    var ParseRange = () => {
      string rangeStr = CellStr(3);
      string[] rangeSplit = rangeStr.Split(':');
      if (rangeSplit.Length == 1) {
        return $"A1:{rangeStr}";
      }

      Debug.Assert(rangeSplit.Length == 2);
      string start = rangeSplit[0];
      string end = rangeSplit[1];
      if (string.IsNullOrWhiteSpace(start)) {
        return $"A1:{end}";
      }

      Debug.Assert(end.Length > 1);
      return rangeStr;
    };

    string range = ParseRange();
    return new(CellStr(1), CellStr(2), range, num);
  }

  readonly MergeExcelUtils _excelUtil = new();
}
